import { login } from '@/api/user'
import { RMenuList } from '@/api/menu'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
// import generateUserRoute from '@/router/generateUserRoute'
import store from '@/store'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { cellphone, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ cellphone: cellphone.trim(), password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async(resolve, reject) => {
      // try {
      //   // 获取用户信息
      //   const userRes = await getInfo(state.token)
      //   // const userData = userRes.data
      //   // eslint-disable-next-line no-unused-vars
      //   let user_name = ''; let role_id = ''; let allRoles = []; let userRoleIds = []
      //   if (userRes.success) {
      //     user_name = (userRes.data || {}).user_name
      //     role_id = (userRes.data || {}).role_id
      //   } else {
      //     reject('获取用户信息失败')
      //   }
      //   // 获取所有的菜单信息
      //   const allRolesRes = await RMenuList()
      //   if (allRolesRes.success) {
      //     allRoles = allRolesRes.data || []
      //   } else {
      //     reject('获取菜单失败')
      //   }
      //   // 获取用户拥有的菜单id
      //   const userRoleIdRes = await getRoleMenu({ role_id })
      //   if (userRoleIdRes.success) {
      //     userRoleIds = userRoleIdRes.data || []
      //   } else {
      //     reject('获取用户失败')
      //   }
      //   // 用户的菜单信息
      //   const roles = allRoles.filter(e => userRoleIds.includes(e.menu_id) || userRoleIds.includes(e.parent_menu_id))
      //   if (!roles.length) {
      //     reject('该用户没有可访问的权限！')
      //   }
      //   const pIds = []
      //   roles.forEach(item => {
      //     if (item.parent_menu_id && !pIds.includes(item.parent_menu_id) && !roles.find(e => e.menu_id === item.parent_menu_id)) {
      //       pIds.push(item.parent_menu_id)
      //     }
      //   })
      //   allRoles.forEach(item => {
      //     if (pIds.includes(item.menu_id)) {
      //       roles.push(item)
      //     }
      //   })
      //   const asyncRoute = await generateUserRoute(roles)
      //   await store.dispatch('permission/setRoutes', asyncRoute)
      //   // asyncRoute.push({ path: '*', redirect: '/404', hidden: true })
      //   router.addRoutes(asyncRoute)
      //   commit('SET_ROLES', roles)
      //   commit('SET_NAME', user_name)
      //   commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
      //   resolve({
      //     user_name,
      //     asyncRoute
      //   })
      // } catch (error) {
      //   reject(error)
      // }
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      router.replace('/login?reload=1')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
